import { request } from '@umijs/max';
import { message, notification } from 'antd';

const showNotificationError = (message: string, description?: string) => {
  notification.error({
    message,
    description,
  });
};

const baseRequest = async (url: string, method: string, params?: any) => {
  try {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `${localStorage.getItem('token')}`
    };
    //TODO: headers上添加自定义内容
    const response = await request(`/api${url}`, {
      method: method,
      headers,
      data: params,
      timeout: 5 * 1000,
    });
    if (response && response.code !== undefined) {
      switch (response.code) {
        case 200:
          // 接口成功
          if (response.msg) message.success(response.msg);
          return Promise.resolve(response.data);
        case response.code >= 500:
          // 接口异常
          message.error(response.msg);
          return Promise.reject(response.msg);
        case 401:
          // 登录失效
          message.error(response.msg);
          return Promise.reject(response.msg);
        default:
          message.error(response.msg);
          return Promise.reject(response);
      }
    } else {
      // 响应结果不是对象
      return Promise.resolve(response);
    }
  } catch (error: any) {
    // console.error('🚀 ~ file: request.ts:33 ~ baseRequest ~ error:', error);
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 登录失效
          break;
        case 403:
          // 没有权限
          break;
        case 404:
          // 接口不存在
          showNotificationError('请求地址不存在', error.config.url);
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
};

// get 下载文件
const FileRequestDownload = async (url: string, method: string, params?: any) => {
  try {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `${localStorage.getItem('token')}`
    };
    //TODO: headers上添加自定义内容
    const response = await request(`/api${url}`, {
      method: method,
      headers,
      data: params,
      responseType: 'blob', // 确保接收二进制数据
      timeout: 5 * 1000,
    });
    if (response && response.code !== undefined) {
      switch (response.code) {
        case 200:
          // 接口成功
          return Promise.resolve(response.data);
        case response.code >= 500:
          // 接口异常
          message.error(response.msg);
          return Promise.reject(response.msg);
        case 401:
          // 登录失效
          message.error(response.msg);
          return Promise.reject(response.msg);
        default:
          message.error(response.msg);
          return Promise.reject(response);
      }
    } else {
      // 响应结果不是对象
      return Promise.resolve(response);
    }
  } catch (error: any) {
    // console.error('🚀 ~ file: request.ts:33 ~ baseRequest ~ error:', error);
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 登录失效
          break;
        case 403:
          // 没有权限
          break;
        case 404:
          // 接口不存在
          showNotificationError('请求地址不存在', error.config.url);
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
};

const formatPageListResult = (data: any) => {
  return {
    data: data,
    success: true,
    total: data.length,
  };
}
const fileRequest = async (url: string, data: any) => {
  try {    
    const headers = {
      'Content-Type': 'multipart/form-data',
      'Authorization': `${localStorage.getItem('token')}`
    };
    //TODO: headers上添加自定义内容
    const response = await request(`/api${url}`, {
      method: "POST",
      headers,
      data: data,
      timeout: 30 * 60,
    });
    if (response && response.code !== undefined) {
      switch (response.code) {
        case 200:
          // 接口成功
          return Promise.resolve(response.data);
        case response.code >= 500:
          // 接口异常
          message.error(response.msg);
          return Promise.reject(response.msg);
        case 401:
          // 登录失效
          message.error(response.msg);
          return Promise.reject(response.msg);
        default:
          message.error(response.msg);
          return Promise.reject(response);
      }
    } else {
      // 响应结果不是对象
      return Promise.resolve(response);
    }
  } catch (error: any) {
    // console.error('🚀 ~ file: request.ts:33 ~ baseRequest ~ error:', error);
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 登录失效
          break;
        case 403:
          // 没有权限
          break;
        case 404:
          // 接口不存在
          showNotificationError('请求地址不存在', error.config.url);
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
}

// springboot 请求
const springBootBaseRequest = async (url: string, method: string, params?: any) => {
  try {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `${localStorage.getItem('token')}`
    };
    //TODO: headers上添加自定义内容
    const response = await request(`/springboot${url}`, {
      method: method,
      headers,
      data: params,
      timeout: 10 * 1000,
    });
    if (response && response.code !== undefined) {
      switch (response.code) {
        case 200:
          // 接口成功
          return Promise.resolve(response.data);
        case response.code >= 500:
          // 接口异常
          message.error(response.msg);
          return Promise.reject(response.msg);
        case 401:
          // 登录失效
          message.error(response.msg);
          return Promise.reject(response.msg);
        default:
          message.error(response.msg);
          return Promise.reject(response);
      }
    } else {
      // 响应结果不是对象
      return Promise.resolve(response);
    }
  } catch (error: any) {
    // console.error('🚀 ~ file: request.ts:33 ~ baseRequest ~ error:', error);
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 登录失效
          break;
        case 403:
          // 没有权限
          break;
        case 404:
          // 接口不存在
          showNotificationError('请求地址不存在', error.config.url);
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
};

/**
 * post 请求
 * @param url
 * @param data
 * @returns
 */
export const post = async (url: string, data?: any) => baseRequest(url, "POST", data);

export const springBootPost = async (url: string, data?: any) => springBootBaseRequest(url, "POST", data);

/**
 * 上传文件
 * @param url 
 * @param data 
 * @returns 
 */
export const uploadFile = async (url: string, data?: any) => fileRequest(url, data);

/**
 * get 请求
 * @param url 
 * @param params 
 * @returns 
 */
export const get = async (url: string, params?: any) => baseRequest(url, "GET", params,);

/**
 * get 请求 下载文件
 * @param url 
 * @param params 
 * @returns 
 */
export const getDownload = async (url: string, params?: any) => FileRequestDownload(url, "GET", params);

/**
 * get 请求table
 * @param url 
 * @param data 
 * @returns 
 */
export const getPages: (url: string, params?: ProTableParams) => Promise<any> = async (url: string, params?: ProTableParams) => {
  try {
    const request = await baseRequest(url, "GET", params);
    return formatPageListResult(request);
  } catch (error) {
    return Promise.reject(error);
  }
};

/**
 * POST 请求下载 ZIP 文件
 * @param url 接口地址
 * @param data POST 请求体数据
 * @returns Promise 对象包含 Blob 数据
 */
const FileRequestPostDownload = async (url: string, method: string, data?: any) => {
  try {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `${localStorage.getItem('token')}`
    };
    
    const response = await request(`/api${url}`, {
      method: method,
      headers,
      data, // POST 请求使用 data 字段传递参数
      responseType: 'blob', // 关键参数：指定响应类型为二进制流
      timeout: 30000000 // 适当延长超时时间
    });

    if (response instanceof Blob) { // 直接返回二进制流
      return Promise.resolve(response);
    }
    return Promise.reject('无效的响应格式');
  } catch (error: any) {
    if (error.response) {
      switch (error.response.status) {
        case 404:
          showNotificationError('请求地址不存在', error.config.url);
          break;
        // 其他状态码处理保持与现有逻辑一致
      }
    }
    return Promise.reject(error);
  }
};

// 导出方法
export const postDownload = async (url: string, data?: any) => FileRequestPostDownload(url, "POST", data);